package com.cloudcc.mobile.im.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrClassicDefaultHeader;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrClassicFrameLayout;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrDefaultHandler;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrFrameLayout;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrHandler;
import com.cloudcc.cloudframe.util.DensityUtils;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.im.Constant;
import com.cloudcc.mobile.im.adapter.GroupAdapter;
import com.cloudcc.mobile.util.GroupComParator;
import com.cloudcc.mobile.util.PinyinUtils;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class GroupsActivity extends BaseActivity implements PtrHandler {
    public static final String TAG = "GroupsActivity";
    private SwipeMenuListView groupListView;
//    protected List<EMGroup> grouplist;
    private GroupAdapter groupAdapter;
    private InputMethodManager inputMethodManager;
    public static GroupsActivity instance;
    private View progressBar;
    private SwipeRefreshLayout swipeRefreshLayout;
    private GroupComParator comParator;
    //	@Bind(R.id.load_more_list_view_ptr_frame)
    private PtrClassicFrameLayout mRefreshLayoutx;
//	Handler handler = new Handler() {
//		public void handleMessage(android.os.Message msg) {
//			swipeRefreshLayout.setRefreshing(false);
//			switch (msg.what) {
//			case 0:
//				refresh();
//				break;
//			case 1:
//				Toast.makeText(GroupsActivity.this,
//						R.string.Failed_to_get_group_chat_information,
//						Toast.LENGTH_LONG).show();
//				break;
//
//			default:
//				break;
//			}
//		};
//	};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.em_fragment_groups);

        instance = this;
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        grouplist = EMGroupManager.getInstance().getAllGroups();
        comParator = new GroupComParator();
        groupListView = (SwipeMenuListView) findViewById(R.id.list);
        mRefreshLayoutx = (PtrClassicFrameLayout) findViewById(R.id.load_more_list_view_ptr_framex);
        //添加listview侧滑删除
        initRefresh();
        initRequestData();

//		swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout);
//		swipeRefreshLayout.setColorSchemeResources(R.color.holo_blue_bright,
//				R.color.holo_green_light, R.color.holo_orange_light,
//				R.color.holo_red_light);
//		// 下拉刷新
//		swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
//
//			@Override
//			public void onRefresh() {
//				EMGroupManager.getInstance().asyncGetGroupsFromServer(
//						new EMValueCallBack<List<EMGroup>>() {
//
//							@Override
//							public void onSuccess(List<EMGroup> value) {
//								handler.sendEmptyMessage(0);
//							}
//
//							@Override
//							public void onError(int error, String errorMsg) {
//								handler.sendEmptyMessage(1);
//							}
//						});
//			}
//		});
		groupListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {

				switch (index) {

					case 0:
						// open
						String st1 = getResources().getString(
								R.string.Exit_the_group_chat_failure);
						new Thread(new Runnable() {
							public void run() {
								try {
									EMGroupManager.getInstance().exitFromGroup(groupAdapter
											.getItem(position - 1).getGroupId());
									runOnUiThread(new Runnable() {
										public void run() {
											setResult(RESULT_OK);
                                            initRequestData();
										}
									});
								} catch (final Exception e) {
									runOnUiThread(new Runnable() {
										public void run() {
											Toast.makeText(
													getApplicationContext(),
													getResources()
															.getString(
																	R.string.Exit_the_group_chat_failure)
															+ " " + e.getMessage(), 1).show();
										}
									});
								}
							}
						}).start();



						break;
//					case 1:
//						// delete
//						break;
				}
				// false : close the menu; true : not close the menu
				return false;
			}
		});
        groupListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //群聊点击
//				if (position == 1) {
//					// 新建群聊
//					startActivityForResult(new Intent(GroupsActivity.this,
//							NewGroupActivity.class), 0);
//				}
//				else
//					{
                // 进入群聊
                Intent intent = new Intent(GroupsActivity.this,
                        ChatActivity.class);
                intent.putExtra("chatType", Constant.CHATTYPE_GROUP);
                intent.putExtra("userId", groupAdapter
                        .getItem(position - 1).getGroupId());
                startActivityForResult(intent, 0);
//				}
            }

        });
        groupListView.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
                    if (getCurrentFocus() != null)
                        inputMethodManager.hideSoftInputFromWindow(
                                getCurrentFocus().getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);
                }
                return false;
            }
        });

    }

    /**
     * 进入公开群聊列表
     */
    public void onPublicGroups(View view) {
        startActivity(new Intent(this, PublicGroupsActivity.class));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onResume() {
        super.onResume();
        initRequestData();
//		refresh();
    }

//    private void refresh() {
//        grouplist = EMGroupManager.getInstance().getAllGroups();
////        try {
////            comParator = new GroupComParator();
////            Collections.sort(grouplist,comParator);
//        groupAdapter = new GroupAdapter(this, 1, grouplist);
////        } catch (Exception e) {
////            e.printStackTrace();
////        }
//        groupListView.setAdapter(groupAdapter);
//        groupAdapter.notifyDataSetChanged();
//
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        instance = null;
    }

    /**
     * 返回
     *
     * @param view
     */
    public void back(View view) {
        finish();
    }
    public int dp2pxx(float dipValue) {
        final float scale = this.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, groupListView,header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        List<EMGroup> grouplist = new ArrayList<>();
        // show group list
         grouplist.addAll(EMGroupManager.getInstance().getAllGroups());
        List<String> listName = new ArrayList<>();
        //筛选以后的list abcd
        List<EMGroup> itemlist = new ArrayList<>();
        //筛选以后的list ###
        List<EMGroup> ewailist = new ArrayList<>();
        if(grouplist.size()>0){
        for (int i = 0;i<grouplist.size();i++){

            try {
                listName.add(PinyinUtils.cn2FirstSpell(grouplist.get(i).getGroupName().substring(0,1)));
            } catch (Exception e) {
                e.printStackTrace();
                ewailist.add(grouplist.get(i));
            }
        }
        //去重lishilist
        for (int i = 0; i < listName.size(); i++) {
            for (int j = listName.size() - 1; j > i; j--) {
                    if (listName.get(i).equals(listName.get(j))) {
                        listName.remove(j);
                    }
            }
        }
        try {
            Collections.sort(listName);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        for (int i = 0; i < listName.size(); i++) {
//            listName.get(i);
//        }
        for(int i = 0; i < listName.size(); i++) {
            for (int j = 0; j < grouplist.size(); j++) {
                if((PinyinUtils.cn2FirstSpell(grouplist.get(j).getGroupName().substring(0,1))).equals(listName.get(i))) {
                    EMGroup emGroup = grouplist.get(j);
                    itemlist.add(emGroup);
                }
            }
        }
        if(ewailist.size()>0) {
            for (int i = 0; i < ewailist.size(); i++) {
                itemlist.add(ewailist.get(i));
            }
        }
        }
//		try {

//            Collections.sort(grouplist,comParator);

//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		groupListView.setMenuCreator(creator);
		groupListView.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT);
        groupAdapter = new GroupAdapter(this, 1, itemlist);
        groupListView.setAdapter(groupAdapter);
        mRefreshLayoutx.refreshComplete();

    }


//    private class MyHeader extends MaterialHeader {
//
//        public MyHeader(Context context) {
//            super(context);
//        }
//
//        public MyHeader(Context context, AttributeSet attrs, int defStyleAttr) {
//            super(context, attrs, defStyleAttr);
//        }
//
//        public MyHeader(Context context, AttributeSet attrs) {
//            super(context, attrs);
//        }
//
//        @Override
//        public void onUIRefreshComplete(PtrFrameLayout frame) {
//            super.onUIRefreshComplete(frame);
//        }
//
//    }

    private void initRequestData() {
        mRefreshLayoutx.postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefreshLayoutx.autoRefresh(true);
            }
        }, 150);
    }

    private void initRefresh() {
        mRefreshLayoutx.setLoadingMinTime(1000);
        mRefreshLayoutx.setPtrHandler(this);
        //1.默认经典头布局
        PtrClassicDefaultHeader header = new PtrClassicDefaultHeader(mContext);
        int[] colors = getResources().getIntArray(R.array.google_colors);
//        header.setColorSchemeColors(colors);
//        header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
//        header.setPadding(0, DensityUtils.dpToPixel(mContext, 10), 0,
//                DensityUtils.dpToPixel(mContext, 5));
//        header.setPtrFrameLayout(mRefreshLayoutx);
        mRefreshLayoutx.setHeaderView(header);
        mRefreshLayoutx.addPtrUIHandler(header);

    }

    SwipeMenuCreator creator = new SwipeMenuCreator() {

        @Override
        public void create(SwipeMenu menu) {
            SwipeMenuItem deleteItem = new SwipeMenuItem(
                    getApplicationContext());
            // set item background
            deleteItem.setBackground(new ColorDrawable(Color.rgb(0xE4, 0x35,
                    0x20)));
            // set item width
            deleteItem.setWidth(dp2pxx(86));
            // set a icon
            deleteItem.setIcon(R.drawable.delete_slidelist);
            // add to menu
            menu.addMenuItem(deleteItem);
        }
    };

}
